package com.haoshuang.zhouzhoubang.utils

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.blankj.utilcode.util.AppUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.utils.toast
import java.io.File

/**
 * Created by zGui on 2022/7/13.
 * 跳转到第三方地图定位处理类
 */
class NavigationUtils {
    companion object {
        val JUMP_GAO_DE = "JUMP_GAO_DE"
        val JUMP_TEN_XUN = "JUMP_TEN_XUN"
        val JUMP_BAI_DU = "JUMP_BAI_DU"
        private val PACKAGE_GAO_DE = "com.autonavi.minimap"  //高德包名
        private val PACKAGE_TEN_XUN = "com.tencent.map"   //腾讯包名
        private val PACKAGE_BAI_DU = "com.baidu.BaiduMap"   //百度包名

        private val TYPE_AROUND = false  //true周边类型 false导航类型

        fun qqToBaidu(lng: Double, lat: Double): Array<Double> {
            val x_pi = 3.14159265358979324 * 3000.0 / 180.0
            val x = lng
            val y = lat
            val z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi)
            val theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi)
            return arrayOf(z * Math.cos(theta) + 0.0065, z * Math.sin(theta) + 0.006)
        }

        /**
         * 跳转地图App
         * type 高德/腾讯/百度
         * lat 目标纬度
         * lon 目标经度
         * poiname 目标名称
         * keyWords TYPE_AROUND = true时，搜索目标附近的关键字
         */
        @JvmStatic
        fun jumpNavigation(context: Context, type: String, lat: String, lon: String, poiname: String) {
            try {
                val intent = Intent()
                when (type) {
                    JUMP_GAO_DE -> {
                        if (isInstall(PACKAGE_GAO_DE)) {
                            if (TYPE_AROUND) {
                                val keyWords = "美食"
                                intent.data =
                                    Uri.parse("androidamap://arroundpoi?sourceApplication=my&keywords=$keyWords&lat=$lat&lon=$lon&dev=0");
                            } else {
                                intent.data =
                                    Uri.parse("androidamap://viewMap?sourceApplication=my&poiname=$poiname&lat=$lat&lon=$lon&dev=0")
                            }
                            context.startActivity(intent)
                        } else {
                            goToMarket(context, PACKAGE_GAO_DE)
                        }
                    }
                    JUMP_TEN_XUN -> {
                        if (isInstall(PACKAGE_TEN_XUN)) {
                            if (TYPE_AROUND) {
                                val keyWords = "篮球场"
                                intent.data =
                                    Uri.parse("qqmap://map/nearby?coord:$lat,$lon;placeName=$keyWords&radius=5000&referer=myapp")
                            } else {
                                intent.data =
                                    Uri.parse("qqmap://map/marker?marker=coord:$lat,$lon;title:$poiname;addr: &referer=myapp")
                            }
                            context.startActivity(intent)
                        } else {
                            goToMarket(context, PACKAGE_TEN_XUN)
                        }
                    }
                    JUMP_BAI_DU -> {
                        if (isInstall(PACKAGE_BAI_DU)) {
                            if (TYPE_AROUND) {
                                val keyWords = "公园"
                                intent.data =  Uri.parse("baidumap://map/place/nearby?query=$keyWords&center=$lat,$lon&radius=1000")
                            } else {
                                intent.data =
                                    Uri.parse("baidumap://map/marker?location=$lat,$lon&title=$poiname&content=&traffic=on")
                            }
                            context.startActivity(intent)
                        } else {
                            goToMarket(context, PACKAGE_BAI_DU)
                        }
                    }
                }
            } catch (e: Exception) {
                toast("请检查是否开启定位权限")
            }
        }


        /**
         * 判断是否安装应用
         */
        private fun isInstall(packageName: String): Boolean {
            /**
             * targetSdkVersion >= 29（Android 11）会强制分区，
             * 默认情况应用外部存储可见性将被过滤，应用需要对分区存储进行适配。
             */
            return AppUtils.isAppInstalled(packageName)
//            return File("/data/data/$packageName").exists()
//                    || File("storage/emulated/0/Android/data/$packageName").exists()
        }

        fun getMapAppList(): Map<String, String>{
            val mapAppMap = mutableMapOf<String, String>()
            if (isInstall(PACKAGE_GAO_DE)){
                mapAppMap["高德地图"] = JUMP_GAO_DE
            }
            if (isInstall(PACKAGE_BAI_DU)){
                mapAppMap["百度地图"] = JUMP_BAI_DU
            }
            if (isInstall(PACKAGE_TEN_XUN)){
                mapAppMap["腾讯地图"] = JUMP_TEN_XUN
            }
            return mapAppMap
        }

        /**
         * 去APP市场下载
         */
        private fun goToMarket(context: Context, packageName: String) {
            try {
                val uri: Uri = Uri.parse("market://details?id=$packageName")
                val goToMarket = Intent(Intent.ACTION_VIEW, uri)
                context.startActivity(goToMarket)
            } catch (e: ActivityNotFoundException) {
            }
        }

        fun startNavigation(context: Context, lat: String, lng: String, address: String){
            val mapAppMap = getMapAppList()
            if (mapAppMap.isEmpty()){
                toast("没有安装任何一款地图软件, 请前往应用市场下载")
                return
            }
            val array = mapAppMap.keys.toList().toTypedArray()
            // 进行导航跳转
            XPopup.Builder(context)
                .asBottomList("", array, ){position, item ->
                    val type = mapAppMap[item]
                    if (type == JUMP_BAI_DU){
                        val latLng = qqToBaidu(lng.toDoubleOrNull()?:0.0, lat.toDoubleOrNull()?:0.0)
                        jumpNavigation(
                            context, type,
                            lat = latLng[1].toString(),
                            lon = latLng[0].toString(),
                            poiname = address.replace("*", ""),
                        )
                    }else {
                        jumpNavigation(
                            context, type!!,
                            lat = lat,
                            lon = lng,
                            poiname = address.replace("*", "") ?: "",
                        )
                    }
                }.show()
        }

    }


}
